package pers.vic.upload.socket.model;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.TimeUnit;

/**
 * 上传速度统计
 * @author Vic.xu
 * @date 2022年6月10日 11:36:11
 */
public class UploadSpeed {
    /**
     * 开始时间
     */
    private long startMills;
    private long total;

    private static final long duration_window = 4000;


    public UploadSpeed() {
        startMills = System.currentTimeMillis();
    }


    /**
     * 计算上传速度：  大小 / 间隔时间
     *  如果间隔时间过长 > 4 sec
     *  则把开始时间向前滑动 2秒，则此时总大小应该减去这2秒的大小
     *
     * @param payloadLength 本次上传的长度
     * @return 下载速度
     */
    public String click(int payloadLength) {
        total += payloadLength;
        long duration = System.currentTimeMillis() - startMills;
        String speed = createSpeed(duration, total);

        //间隔过长 则缩短间隔 使之更接近瞬时速度
        if (duration > 4000) {
            total = (total / duration) * (duration -  2000);
            startMills += 2000;
        }

        return speed;
    }

    private String createSpeed(long duration, long length) {
        if (duration < 1) {
            duration = 1000;
        }
        double speed = length * 1.0 / duration * 1000;
        if (speed < 1024) {
            return Math.round(speed) + "B/S";
        }
        speed = speed / 1024;
        if (speed < 1024) {
            return Math.round(speed) + "KB/S";
        }
        speed = speed / 1024;
        return new BigDecimal(String.valueOf(speed)).setScale(1, RoundingMode.FLOOR).toPlainString() + "MB/S";
    }
}
